//
//  ESTLoginViewController.m
//  ESTSCRMAPP
//
//  Created by 李贤立 on 2018/9/20.
//  Copyright © 2018年 Capfer. All rights reserved.
//

#import "ESTLoginViewController.h"
#import "TYZTabBarController.h"
#import "TYZNavigationController.h"
#import "ESTActivityViewController.h"
#import "ESTUserInfo.h"
#import "ESTLoginTool.h"
#import "ESTAppVersionModel.h"
#import "ESTActivityViewController.h"
#define Placeholder_UserName [@"请输入用户名" S]
#define Placeholder_Password [@"请输入密码" S]
#define Login_Name           [@"登录" S]
#define Login_Name2          [@"登录阿坤电脑" S]
#define Login_Name3          [@"登录吴总电脑" S]
#define UserNameMaxLength    15
#define UserNameMinLength    1
#define PasswordMaxLength    15
#define PasswordMinLength    6
#define UserNameTag          TAG_LOGIN_USERNAMETEXTFIELD
#define PasswordTag          TAG_LOGIN_PASSWORDTEXTFIELD
@interface ESTLoginViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIView *userNameView;
@property (weak, nonatomic) IBOutlet UITextField *nameTextField;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
@property (weak, nonatomic) IBOutlet UIView *passwordView;
@property (weak, nonatomic) IBOutlet UIButton *loginButton;
@property (weak, nonatomic) IBOutlet UIButton *loginButton2;
@property (weak, nonatomic) IBOutlet UIButton *loginButton3;
@property (weak, nonatomic) IBOutlet UIView *progressView;
@property (weak, nonatomic) IBOutlet UILabel *progressLabel;
@property (weak, nonatomic) IBOutlet UIView *valueView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *progressValue;
/**
 *  用户名
 */
@property(nonatomic, copy) NSString *userName;
/**
 *  密码
 */
@property(nonatomic, copy) NSString *password;
/**
 *  进度条长度
 */
@property(nonatomic, assign) CGFloat progressLength;
/**
 *  是否可以登录了（获取到deviceToken）
 */
@property(nonatomic, assign) BOOL startLogin;
@end

@implementation ESTLoginViewController
#pragma mark - 生命周期方法
- (void)viewDidLoad {
    [super viewDidLoad];
    self.nameTextField.tag = UserNameTag;
    self.passwordTextField.tag = PasswordTag;
    self.nameTextField.text = Placeholder_UserName;
    self.passwordTextField.text = Placeholder_Password;
    self.passwordView.hidden = NO;
    self.userNameView.hidden = NO;
    self.loginButton.hidden = NO;
    self.loginButton.tag = TAG_LOGIN_LOGINBUTTON;
#ifdef DEBUG
    self.loginButton2.hidden = NO;
    self.loginButton3.hidden = NO;
    self.loginButton2.tag = TAG_LOGIN_LOGINBUTTON2;
    self.loginButton3.tag = TAG_LOGIN_LOGINBUTTON3;
#else
    [self.loginButton2 removeFromSuperview];
    [self.loginButton3 removeFromSuperview];
#endif
    self.progressView.hidden = YES;
    self.progressLabel.hidden = YES;
    TYZButton *nameClearButton = [[TYZButton alloc] initWithFrame:CGRectMake(0, 0, 15, 15)];
    nameClearButton.tag = UserNameTag + 5;
    [nameClearButton setBackgroundImage:[UIImage imageNamed:@"textField_clear"] forState:UIControlStateNormal];
    [nameClearButton addTarget:self action:@selector(didClickTextFieldClearButton:) forControlEvents:UIControlEventTouchUpInside];
    self.nameTextField.rightViewMode = UITextFieldViewModeWhileEditing;
    self.nameTextField.rightView = nameClearButton;
    TYZButton *passwordClearButton = [[TYZButton alloc] initWithFrame:CGRectMake(0, 0, 15, 15)];
    passwordClearButton.tag = PasswordTag + 5;
    [passwordClearButton setBackgroundImage:[UIImage imageNamed:@"textField_clear"] forState:UIControlStateNormal];
    [passwordClearButton addTarget:self action:@selector(didClickTextFieldClearButton:) forControlEvents:UIControlEventTouchUpInside];
    self.passwordTextField.rightViewMode = UITextFieldViewModeWhileEditing;
    self.passwordTextField.rightView = passwordClearButton;
    dispatch_async(dispatch_get_main_queue(), ^{
        self.userNameView.layer.cornerRadius = CGRectGetHeight(self.userNameView.bounds) * 0.5;
        self.userNameView.layer.borderWidth = 1;
        self.userNameView.layer.borderColor = [UIColor whiteColor].CGColor;
        self.passwordView.layer.cornerRadius = CGRectGetHeight(self.passwordView.bounds) * 0.5;
        self.passwordView.layer.borderWidth = 1;
        self.passwordView.layer.borderColor = [UIColor whiteColor].CGColor;
        self.loginButton.layer.cornerRadius = CGRectGetHeight(self.loginButton.bounds) * 0.5;
        self.loginButton2.layer.cornerRadius = CGRectGetHeight(self.loginButton2.bounds) * 0.5;
        self.loginButton3.layer.cornerRadius = CGRectGetHeight(self.loginButton3.bounds) * 0.5;
        self.progressView.layer.borderWidth = 1;
        self.progressView.layer.borderColor = [UIColor whiteColor].CGColor;
        self.progressView.layer.cornerRadius = CGRectGetHeight(self.progressView.bounds) * 0.5;
        self.valueView.layer.cornerRadius = CGRectGetHeight(self.valueView.bounds) * 0.5;
        self.progressLength = CGRectGetWidth(self.progressView.bounds);
        [self.loginButton setTitle:Login_Name forState:UIControlStateNormal];
        [self.loginButton setTitleColor:TYZBlueColor forState:UIControlStateNormal];
        [self.loginButton2 setTitle:Login_Name2 forState:UIControlStateNormal];
        [self.loginButton2 setTitleColor:TYZBlueColor forState:UIControlStateNormal];
        [self.loginButton3 setTitle:Login_Name3 forState:UIControlStateNormal];
        [self.loginButton3 setTitleColor:TYZBlueColor forState:UIControlStateNormal];
    });
    WEAKSELF
    [[NSNotificationCenter defaultCenter] addObserverForName:Notification_GetDeviceTokenSuccess object:nil queue:[NSOperationQueue currentQueue] usingBlock:^(NSNotification * _Nonnull note) {
        if (CoreInfo.isLogined) {
            self.password = self.passwordTextField.text = CoreInfo.password;
            if (self.userName.length > 0 && self.password.length >= 6) {
                self.passwordTextField.secureTextEntry = YES;
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
#ifdef DEBUG
                    weakSelf.startLogin = YES;
#ifdef AUTOLOGIN
                    [self handleLogin:nil];
#endif
#else
                    // 检测版本
                    WEAKSELF
                    [ESTAppVersionModel checkAppVersionWithComplement:^{
                        weakSelf.startLogin = YES;
#ifdef AUTOLOGIN
                        [weakSelf handleLogin:nil];
#endif
                    }];
#endif
                });
            }
        } else {
            weakSelf.startLogin = YES;
        }
    }];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    WEAKSELF
    [[NSNotificationCenter defaultCenter] addObserverForName:UITextFieldTextDidChangeNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        UITextField *textField = (UITextField *)note.object;
        if (textField.tag == UserNameTag) {
            weakSelf.userName = textField.text;
        } else if (textField.tag == PasswordTag) {
            weakSelf.password = textField.text;
        }
    }];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if (CoreInfo.userName.length > 0) {
        self.userName = self.nameTextField.text = CoreInfo.userName;
    }
    if (CoreInfo.isLogined) {
        self.password = self.passwordTextField.text = CoreInfo.password;
        if (self.userName.length > 0 && self.password.length >= 6) {
            
        } else {
            self.userName = self.nameTextField.text = CoreInfo.userName = @"";
            self.password = self.passwordTextField.text = CoreInfo.password = @"";
            self.passwordTextField.secureTextEntry = NO;
        }
    }
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
//    self.navigationController.navigationBarHidden = NO;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)didClickTextFieldClearButton:(TYZButton *)button {
    if (button.tag == UserNameTag + 5) {
        self.userName = @"";
        self.password = @"";
        self.nameTextField.text = Placeholder_UserName;
        self.passwordTextField.text = Placeholder_Password;
        self.passwordTextField.secureTextEntry = NO;
    } else if (button.tag == PasswordTag + 5) {
        self.password = @"";
        self.passwordTextField.text = Placeholder_Password;
    }
}
#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if (textField.tag == UserNameTag) {
        if (self.userName.length > 0) {
            textField.text = self.userName;
        } else {
            self.nameTextField.text = @"";
        }
        return YES;
    }
    if (textField.tag == PasswordTag) {
        self.password = @"";
        self.passwordTextField.text = @"";
        self.passwordTextField.secureTextEntry = YES;
        return YES;
    }
    return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    if (textField.tag == UserNameTag) {
        self.passwordTextField.text = Placeholder_Password;
    }
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    if (textField.tag == UserNameTag) {
        if (self.userName.length == 0) {
            self.nameTextField.text = Placeholder_UserName;
        }
        return YES;
    }
    if (textField.tag == PasswordTag) {
        if (self.password.length == 0) {
            self.passwordTextField.text = Placeholder_Password;
            self.passwordTextField.secureTextEntry = NO;
        }
        return YES;
    }
    return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField.tag == UserNameTag) {
        [self.nameTextField resignFirstResponder];
        [self.passwordTextField becomeFirstResponder];
        return YES;
    }
    if (textField.tag == PasswordTag) {
        [self.passwordTextField resignFirstResponder];
        [self handleLogin:nil];
        return YES;
    }
    return YES;
}
#pragma mark - action
- (IBAction)handleLogin:(UIButton *)sender {
    if (self.startLogin == NO) {
        [TYZLoadingView showNormal:[@"请稍等..." S]];
        return;
    }
    BaseInfo.connectType = sender.tag - TAG_LOGIN_LOGINBUTTON;
#ifdef DEBUG
    if (self.userName.length == 0) {
        self.userName = @"A";
    }
    if (self.password.length == 0) {
        self.password = @"888888";
        if (BaseInfo.connectType == CONNECT_WU) {
            self.password = @"8";
        }
    }
#else
#endif
    if (self.userName.length == 0) {
        [TYZLoadingView showError:@"请输入用户名"];
        return;
    }
    if (self.userName.length > 15) {
        [TYZLoadingView showError:@"用户名长度不能超过15位"];
        return;
    }
    if (self.password.length == 0) {
        [TYZLoadingView showError:@"请输入密码"];
        return;
    }
    if (self.password.length < 6) {
        [TYZLoadingView showError:@"密码长度不能小于6位"];
        return;
    }
    if (self.password.length > 15) {
        [TYZLoadingView showError:@"密码长度不能超过15位"];
        return;
    }
    WEAKSELF
    [TYZLoadingView showMessage:nil];
    [ESTLoginTool loginWithUserAccount:self.userName password:self.password loginSuccess:^(NSInteger integer){
        [TYZLoadingView hideHUD];
        switch (integer) {
            case 0:
                CoreInfo.isLogined = YES;
                CoreInfo.userName = weakSelf.userName;
                CoreInfo.password = weakSelf.password;
                weakSelf.password = @"";
                weakSelf.passwordTextField.text = Placeholder_Password;
                weakSelf.passwordTextField.secureTextEntry = NO;
                weakSelf.passwordView.hidden = YES;
                weakSelf.userNameView.hidden = YES;
                weakSelf.loginButton.hidden = YES;
                weakSelf.loginButton2.hidden = YES;
                weakSelf.loginButton3.hidden = YES;
                weakSelf.progressView.hidden = NO;
                weakSelf.progressLabel.hidden = NO;
                weakSelf.progressLabel.text = @"0%";
                weakSelf.progressValue.constant = 0;
                break;
            case 1:
                weakSelf.progressLabel.text = @"25%";
                weakSelf.progressValue.constant = weakSelf.progressLength * 0.25;
                break;
            case 2:
                weakSelf.progressLabel.text = @"50%";
                weakSelf.progressValue.constant = weakSelf.progressLength * 0.50;
                break;
            case 3:
                weakSelf.progressLabel.text = @"75%";
                weakSelf.progressValue.constant = weakSelf.progressLength * 0.75;
                break;
            case 4:
                weakSelf.progressLabel.text = @"100%";
                weakSelf.progressValue.constant = weakSelf.progressLength * 1;
                break;
            default:
                break;
        }
    } complement:^(NSString *result) {
        if ([result isEqualToString:Login_Success]) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(Value_VisionStopOverTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                // 确定主题
                UIViewController *controller;
#ifdef ACTIVITY
                controller = [[ESTActivityViewController alloc] init];
#else
                if (UserInfo.login_user_type == USER_TYPE_ACTIVITY_COMMISSIONER) {
                    controller = [[ESTActivityViewController alloc] init];
                } else {
                    controller = [[TYZTabBarController alloc] init];
                }
#endif
                [weakSelf presentViewController:[[TYZNavigationController alloc] initWithRootViewController:controller] animated:YES completion:^{
                        weakSelf.passwordView.hidden = NO;
                        weakSelf.userNameView.hidden = NO;
                        weakSelf.loginButton.hidden = NO;
                        weakSelf.loginButton2.hidden = NO;
                        weakSelf.loginButton3.hidden = NO;
                        weakSelf.progressView.hidden = YES;
                        weakSelf.progressLabel.hidden = YES;
                        weakSelf.nameTextField.text = weakSelf.userName;
                    }];
                });
        } else {
            [TYZLoadingView showError:result];
        }
    }];
}
@end
